package com.redis.demo.annotation.aop;

import com.redis.demo.annotation.LockTest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @author Admin
 * @date 2024/6/15 11:28
 */
@Component
@Aspect
public class LockTestAop {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Pointcut("@annotation(com.redis.demo.annotation.LockTest)")
    public void LockTestAop() {

    }

    @Around("LockTestAop() && @annotation(lockTest)")
    public Object aspectLockTestAop(ProceedingJoinPoint joinPoint, LockTest lockTest) {
        RLock lock = redissonClient.getLock(lockTest.key());
        boolean flag = false;
        try {
            flag = lock.tryLock(1, lockTest.expired(), TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
            if (flag) {
                try {
                    Thread.sleep(2000);
                    return joinPoint.proceed();
                } catch (Throwable e) {
                    throw new RuntimeException(e);
                }finally {
                    lock.unlock();
                }
            }




        return null;
    }
}
